package main
import (
	"fmt"
	"math/rand"
	"time"
	"os"
	"bufio"
	"strconv"
	"sort"
	"io"
	"strings"
)

func main(){
	exitwritechan := make(chan bool,1)
	exitreadchan := make(chan bool,1)
	go writeDataToFile(exitwritechan)
	for v := range exitwritechan{
		fmt.Println("1000个数据写完了吗？写完才能继续往下执行。",v)
	}
	go Sortrw(exitreadchan)
	for v := range exitreadchan{
		fmt.Println("1000个数据排序重写完了吗？写完才能继续往下执行。",v)
	}
	fmt.Println("全部协程执行完毕！")
}

func writeDataToFile(exitwritechan chan bool){
	rand.Seed(time.Now().UnixNano())
	writefile,err:=  os.OpenFile("d:/uploadfiles/channel.txt",os.O_WRONLY | os.O_CREATE,0666)
	if err != nil{
		fmt.Println("文件打开失败，Error：",err)
		return
	}
	defer writefile.Close()
	writer := bufio.NewWriter(writefile)
	for i:=0;i<1000;i++{
		num := rand.Intn(1000)+1
		writer.WriteString(strconv.Itoa(num)+"\r\n")
	}
	writer.Flush()
	exitwritechan <- true
	close(exitwritechan)
}
func Sortrw(exitreadchan chan bool){
	var numslice []int
	readfile,rerr := os.Open("d:/uploadfiles/channel.txt")
	if rerr != nil{
		fmt.Println("文件打开失败，Error：",rerr)
		return
	}
	writefile,werr := os.OpenFile("d:/uploadfiles/channel_sort.txt",os.O_WRONLY | os.O_CREATE,0666)
	if werr != nil{
		fmt.Println("文件打开失败，Error：",werr)
		return
	}
	defer readfile.Close()
	defer writefile.Close()
	reader := bufio.NewReader(readfile)
	writer := bufio.NewWriter(writefile)
	for {
		num,err :=reader.ReadString('\n') //读到换行就结束
		if err == io.EOF{  //io.EOF表示文件的末尾
			break
		}
		fmt.Printf("num's Type :%T -- num's value :%v",num,num)
		num = strings.Trim(num," \n\r")
		n,_ := strconv.Atoi(num)
		numslice = append(numslice,n)
	}
	sort.Ints(numslice)

	for i:=0;i<len(numslice);i++{
		writer.WriteString(strconv.Itoa(numslice[i])+"\r\n")
	}
	writer.Flush()
	exitreadchan <- true
	close(exitreadchan)
}